package com.lottery.im.module.chat.presenter;

import android.app.Activity;
import com.lottery.im.MyApplication;
import com.lottery.im.api.Api;
import com.lottery.im.api.ApiClient;
import com.lottery.im.api.observer.BaseObserver;
import com.lottery.im.api.result.entity.FaceUrl;
import com.lottery.im.base.BaseFragmentPresenter;
import com.lottery.im.module.chat.view.GroupProfileView;
import com.lottery.im.module.tim.event.RefreshEvent;
import com.lottery.im.module.tim.model.GroupInfo;
import com.lottery.im.util.SPUtils;
import com.tencent.imsdk.TIMCallBack;
import com.tencent.imsdk.TIMConversation;
import com.tencent.imsdk.TIMConversationType;
import com.tencent.imsdk.TIMFriendshipManager;
import com.tencent.imsdk.TIMGroupManager;
import com.tencent.imsdk.TIMGroupMemberInfo;
import com.tencent.imsdk.TIMGroupMemberRoleType;
import com.tencent.imsdk.TIMGroupReceiveMessageOpt;
import com.tencent.imsdk.TIMManager;
import com.tencent.imsdk.TIMMessage;
import com.tencent.imsdk.TIMUserProfile;
import com.tencent.imsdk.TIMValueCallBack;
import com.tencent.imsdk.ext.group.TIMGroupDetailInfo;
import com.tencent.imsdk.ext.group.TIMGroupManagerExt;
import com.tencent.imsdk.ext.group.TIMGroupSelfInfo;
import com.tencent.imsdk.ext.message.TIMConversationExt;
import com.trello.rxlifecycle2.LifecycleProvider;
import com.trello.rxlifecycle2.android.FragmentEvent;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class GroupProfilePresenter extends BaseFragmentPresenter<GroupProfileView> {

  public GroupProfilePresenter(Activity activity,
      GroupProfileView iView,
      LifecycleProvider<FragmentEvent> provider) {
    super(activity, iView, provider);
  }

  /**
   * 获取自己的群内资料 （其他资料GroupInfo已做缓存，主要目前是获取我的群名片）
   *
   * @param identify 群ID
   */
  public void getSelfInfo(String identify) {
    TIMGroupManagerExt.getInstance().getSelfInfo(identify,
        new TIMValueCallBack<TIMGroupSelfInfo>() {
          @Override public void onError(int i, String s) {

          }

          @Override public void onSuccess(TIMGroupSelfInfo timGroupSelfInfo) {
            if (null == iView) return;
            iView.setNameCard(timGroupSelfInfo.getNameCard());
          }
        });
  }

  /**
   * 获取群详细信息，主要是用于是否全员禁言（由于全员禁言没有回调）
   *
   * @param identify 群ID
   */
  public void getGroupDetailInfo(String identify) {
    List<String> ids = new ArrayList<>();
    ids.add(identify);
    TIMGroupManagerExt.getInstance().getGroupDetailInfo(ids,
        new TIMValueCallBack<List<TIMGroupDetailInfo>>() {
          @Override public void onError(int i, String s) {

          }

          @Override public void onSuccess(List<TIMGroupDetailInfo> timGroupDetailInfos) {
            if (null == iView) return;
            TIMGroupDetailInfo detailInfo = timGroupDetailInfos.get(0);
            iView.isSilenceAll(detailInfo.isSilenceAll());
          }
        });
  }

  /**
   * 获取群成员列表
   *
   * @param type 是否首次获取
   * @param dentify 群ID
   */
  public void getGroupMembers(int type, String dentify) {
    if (null == iView) return;
    if (type == 1) {
      iView.showLoadingDialog();
    }
    TIMGroupManagerExt.getInstance().getGroupMembers(dentify,
        new TIMValueCallBack<List<TIMGroupMemberInfo>>() {
          @Override public void onError(int i, String s) {
            if (null == iView) return;
            if (type == 1) {
              iView.showToast("获取群资料失败～");
            } else {
              iView.showToast("刷新群资料失败～");
            }
            iView.cancelLoadingDialog();
          }

          @Override public void onSuccess(List<TIMGroupMemberInfo> timGroupMemberInfos) {
            if (null == iView) return;
            iView.cancelLoadingDialog();
            iView.showMemberInfo(timGroupMemberInfos);
          }
        });
  }

  /**
   * 获取用户信息，主要是由于获取到的群成员信息只有ID，其他都是空
   *
   * @param ids 用户ID列表
   */
  public void getUsersProfile(List<String> ids) {
    TIMFriendshipManager.getInstance().getUsersProfile(ids,
        new TIMValueCallBack<List<TIMUserProfile>>() {
          @Override public void onError(int i, String s) {

          }

          @Override public void onSuccess(List<TIMUserProfile> timUserProfiles) {
            if (null == iView) return;
            iView.refreshUsersProfile(timUserProfiles);
          }
        });
  }

  /**
   * 消息免打扰开关
   *
   * @param groupId 群ID
   * @param isReceive 是否接收
   */
  public void setReceiveMessageOpt(String groupId, boolean isReceive) {
    iView.showLoadingDialog();
    TIMGroupManagerExt.ModifyMemberInfoParam param =
        new TIMGroupManagerExt.ModifyMemberInfoParam(groupId,
            MyApplication.getInstance().getThirdAccId());
    if (isReceive) {
      param.setReceiveMessageOpt(TIMGroupReceiveMessageOpt.ReceiveAndNotify);
    } else {
      param.setReceiveMessageOpt(TIMGroupReceiveMessageOpt.ReceiveNotNotify);
    }

    TIMGroupManagerExt.getInstance().modifyMemberInfo(param, new TIMCallBack() {
      @Override
      public void onError(int code, String desc) {
        if (null == iView) return;
        iView.setReceiveMessageOptFail();
        iView.cancelLoadingDialog();
      }

      @Override
      public void onSuccess() {
        if (null == iView) return;
        iView.cancelLoadingDialog();
      }
    });
  }

  /**
   * 全体禁言
   *
   * @param groupId 群ID
   * @param isSilence 是否禁言
   */
  public void setSilence(String groupId, boolean isSilence) {
    iView.showLoadingDialog();
    TIMGroupManagerExt.ModifyGroupInfoParam param =
        new TIMGroupManagerExt.ModifyGroupInfoParam(groupId);
    param.setSilenceAll(isSilence);
    TIMGroupManagerExt.getInstance().modifyGroupInfo(param, new TIMCallBack() {
      @Override
      public void onError(int code, String desc) {
        if (null == iView) return;
        iView.setSilenceFail();
        iView.cancelLoadingDialog();
      }

      @Override
      public void onSuccess() {
        if (null == iView) return;
        iView.setSilenceSuc();
        iView.cancelLoadingDialog();
      }
    });
  }

  /**
   * 清空消息
   *
   * @param identify 群ID
   */
  public void clearMessage(String identify) {

    TIMConversation conversation =
        TIMManager.getInstance().getConversation(TIMConversationType.Group, identify);
    TIMConversationExt conversationExt = new TIMConversationExt(conversation);

    conversationExt.getLocalMessage(1, null, new TIMValueCallBack<List<TIMMessage>>() {
      @Override public void onError(int i, String s) {
        deleteLocalMessage(conversationExt);
      }

      @Override public void onSuccess(List<TIMMessage> timMessages) {
        if (timMessages.size() > 0) {
          SPUtils.put(MyApplication.getInstance(), identify, timMessages.get(0).timestamp());
        }
        deleteLocalMessage(conversationExt);
      }
    });
  }

  private void deleteLocalMessage(TIMConversationExt conversationExt) {
    conversationExt.deleteLocalMessage(new TIMCallBack() {
      @Override public void onError(int i, String s) {
        if (null == iView) return;
        iView.showToast("删除失败,请重试～");
      }

      @Override public void onSuccess() {
        if (null == iView) return;
        iView.showToast("成功删除群历史聊天记录");
        RefreshEvent.getInstance().onRefresh();
      }
    });
  }

  /**
   * 群头像修改（先上传自己的服务器，再将URL上传至TIM）
   *
   * @param identify 群ID
   * @param path 文件地址
   */
  public void updateGroupFaceUrl(String identify, String path) {

    File file = new File(path);
    MultipartBody.Builder builder = new MultipartBody.Builder()
        .setType(MultipartBody.FORM)//表单类型
        .addFormDataPart("userId", MyApplication.getInstance().getUserInfo().getUserId())
        .addFormDataPart("token", MyApplication.getInstance().getToken())
        .addFormDataPart("groupId", identify);
    RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
    builder.addFormDataPart("faceUrl", file.getName(), imageBody);//imgfile 后台接收图片流的参数名
    List<MultipartBody.Part> parts = builder.build().parts();

    ApiClient.getApiRetrofitInstance()
        .updateGroupFaceUrl(parts)
        .throttleFirst(2, TimeUnit.SECONDS)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .compose(provider.bindToLifecycle())
        .subscribe(new BaseObserver<FaceUrl>() {
          @Override public void onStart() {
            iView.showLoadingDialog();
          }

          @Override public void onSuccess(FaceUrl groupFaceUrl) {
            TIMGroupManagerExt.ModifyGroupInfoParam param =
                new TIMGroupManagerExt.ModifyGroupInfoParam(identify);
            param.setFaceUrl(Api.BASEADDRESS + groupFaceUrl.getFaceUrl());
            TIMGroupManagerExt.getInstance().modifyGroupInfo(param, new TIMCallBack() {
              @Override
              public void onError(int code, String desc) {
                if (null == iView) return;
                iView.showToast("上传失败，请稍后再试");
                iView.cancelLoadingDialog();
              }

              @Override
              public void onSuccess() {
                if (null == iView) return;
                iView.updateGroupFaceUrl(Api.BASEADDRESS + groupFaceUrl.getFaceUrl());
                iView.cancelLoadingDialog();
              }
            });
          }

          @Override public void onFail(String code, String msg) {
            iView.showToast(msg);
            iView.cancelLoadingDialog();
          }

          @Override public void onException(String msg) {

          }

          @Override public void onFinish() {

          }
        });
  }

  /**
   * 群组操作（解散、退出）
   *
   * @param identify 群ID
   */
  public void operation(String identify) {
    iView.showLoadingDialog();
    if (GroupInfo.getInstance().getRole(identify) == TIMGroupMemberRoleType.Owner) {
      // 解散
      TIMGroupManagerExt.getInstance().deleteGroup(identify, new TIMCallBack() {
        @Override public void onError(int i, String s) {
          if (null == iView) return;
          iView.showToast("解散群聊失败，请稍后再试～");
          iView.cancelLoadingDialog();
        }

        @Override public void onSuccess() {
          if (null == iView) return;
          iView.operationSuc();
          iView.cancelLoadingDialog();
        }
      });
    } else {
      // 退出
      TIMGroupManager.getInstance().quitGroup(identify, new TIMCallBack() {
        @Override public void onError(int i, String s) {
          if (null == iView) return;
          iView.showToast("退出群聊失败，请稍后再试～");
          iView.cancelLoadingDialog();
        }

        @Override public void onSuccess() {
          if (null == iView) return;
          iView.operationSuc();
          iView.cancelLoadingDialog();
        }
      });
    }
  }
}
